package by.pavlyukevich.paymentsystem.panel.user;

import java.util.Date;

import javax.inject.Inject;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.bean.validation.PropertyValidator;
import org.apache.wicket.event.Broadcast;
import org.apache.wicket.extensions.markup.html.form.DateTextField;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;

import by.pavlyukevich.paymentsystem.add.ErrorEvent;
import by.pavlyukevich.paymentsystem.add.PanelUpdateEvent;
import by.pavlyukevich.paymentsystem.datamodel.user.Individual;
import by.pavlyukevich.paymentsystem.services.user.IndividualService;

public class IndividualEditPanel extends Panel {
	@Inject
	IndividualService individualService;

	public IndividualEditPanel(String id, Individual individual, Panel respPanel) {
		super(id);
		setOutputMarkupId(true);

		Form<Individual> form = new Form<Individual>("form", new CompoundPropertyModel<Individual>(
				individual));
		add(form);

		form.add(new TextField<String>("family").add(new PropertyValidator<String>()));
		form.add(new TextField<String>("name").add(new PropertyValidator<String>()));
		form.add(new DateTextField("birthday", "dd.MM.yyyy").add(new PropertyValidator<Date>()));

		form.add(new TextField<String>("email").add(new PropertyValidator<String>()));
		form.add(new AjaxSubmitLink("save") {
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				individualService.saveOrUpdate(individual);
				send(getPage(), Broadcast.BREADTH, new PanelUpdateEvent(target, respPanel));
			}

			@Override
			protected void onError(AjaxRequestTarget target, Form<?> form) {
				send(getPage(), Broadcast.BREADTH, new ErrorEvent(target));
			}

		});

	}

}
